package com.yanx.framework.web.domain.server;

import cn.hutool.core.util.NumberUtil;
import com.yanx.common.utils.DateTime_;
import lombok.Setter;

import java.lang.management.ManagementFactory;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * JVM相关信息
 *
 * @author gotanks
 */
@Setter
public class Jvm {
    /**
     * 当前JVM占用的内存总数(M)
     */
    private double total;

    /**
     * JVM最大可用内存总数(M)
     */
    private double max;

    /**
     * JVM空闲内存(M)
     */
    private double free;

    /**
     * JDK版本
     */
    private String version;

    /**
     * JDK路径
     */
    private String home;

    public double getTotal() {
        return NumberUtil.div(total, (1024 * 1024), 2);
    }

    public double getMax() {
        return NumberUtil.div(max, (1024 * 1024), 2);
    }

    public double getFree() {
        return NumberUtil.div(free, (1024 * 1024), 2);
    }

    public double getUsed() {
        return NumberUtil.div(total - free, (1024 * 1024), 2);
    }

    public double getUsage() {
        return NumberUtil.mul(NumberUtil.div(total - free, total, 4), 100);
    }

    /**
     * 获取JDK名称
     */
    public String getName() {
        return ManagementFactory.getRuntimeMXBean().getVmName();
    }

    public String getVersion() {
        return version;
    }

    public String getHome() {
        return home;
    }

    /**
     * JDK启动时间
     */
    public String getStartTime() {
        return DateTime_.parseString(getServerStartDate());
    }

    /**
     * JDK运行时间
     */
    public String getRunTime() {
        Duration duration = Duration.between(getServerStartDate(), LocalDateTime.now());
        return duration.toDays() + "天" + duration.toHours() + "小时" + duration.toMinutes() + "分钟";
    }


    /**
     * 获取服务器启动时间
     *
     * @return
     */
    private static LocalDateTime getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return DateTime_.parseDateTime(time);
    }
}
